<?php

/**
 * ResetPasswordForm 重置密码表单模型
 *
 * @author Hua Yang <htmlcook@gmail.com>
 * @package backend.models
 */
class ResetPasswordForm extends CFormModel
{
	/**
	 * @var string
	 */
	public $password;

	/**
	 * @var string
	 */
	public $password_repeat;

	/**
	 * @var string
	 */
	private $_token;

	/**
	 * @var User 用户
	 */
	private $_user;

	public function __construct($token, $scenario = '')
	{
		$this->_token = $token;
		$this->_user = User::model()->findByPasswordResetToken($this->_token);
		parent::__construct($scenario);
	}

	/**
	 * 验证规则
	 *
	 * @see CModel::rules()
	 */
	public function rules()
	{
		return array(
			array('password, password_repeat', 'required'),
			array('password', 'compare'),
		);
	}

	/**
	 * 属性标签
	 *
	 * @see CModel::attributeLabels()
	 */
	public function attributeLabels()
	{
		return array(
			'password' => '新密码',
			'password_repeat' => '确认密码',
		);
	}

	/**
	 * 重置密码
	 */
	public function resetPassword()
	{
		if (!isset($this->_user)) {
			return false;
		}

		$this->_user->removeToken();
		$this->_user->setPassword($this->password);
		return $this->_user->save(false, array('token', 'password_hash'));
	}

	/**
	 * 获取用户
	 *
	 * @return User
	 */
	public function getUser()
	{
		if (!isset($this->_user)) {
			$this->_user = User::model()->findByPasswordResetToken($this->_token);
		}
		return $this->_user;
	}
}